﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace FourKill.Engine
{
    public class ViewPort : IViewPort
    {
        private double _scale;
        private Size _size = new Size(200, 100);
        private double _unitHeight = 3;
        private double _unitWidth = 6;
        private double _distanceToView;
        private double _horizontalViewableAngle;
        private double _verticalViewableAngle;

        public ViewPort(double unitWidth, double horizontalViewableAngle, double verticalViewableAngle)
        {
            _unitWidth = unitWidth;
            _horizontalViewableAngle = horizontalViewableAngle;
            _verticalViewableAngle = verticalViewableAngle;
            Recalculate();
        }

        public double WidthOfView 
        { 
            get { return _unitWidth; }
            set
            {
                _unitWidth = value;
                Recalculate();
            }
        }

        public double HeightOfView
        {
            get { return _unitHeight; }
            set
            {
                _unitHeight = value;
                Recalculate(true);
            }
        }

        public double DistanceToView
        {
            get
            {
                return _distanceToView;
            }
        }

        public double HorizontalViewableAngle
        {
            get { return _horizontalViewableAngle; }
            set 
            { 
                _horizontalViewableAngle = value;
                Recalculate();
            }
        }

        public double VerticalViewableAngle
        {
            get { return _verticalViewableAngle; }
            set
            {
                _verticalViewableAngle = value;
                Recalculate(true);
            }
        }

        public bool IsInView(double angle) { return true; }
        
        public double Scale
        {
            get
            {
                return _size.Width / WidthOfView;
            }
        }

        public Size PixelSize
        {
            get { return _size; }
            set
            {
                _size = value;
                Recalculate();
            }
        }

        private void Recalculate(bool useHeight = false)
        {
            if (useHeight)
            {
                _scale = _size.Height / _unitHeight;
                _unitWidth = _size.Width / _scale;
                _distanceToView = (_unitHeight / 2d) / Math.Atan(_verticalViewableAngle);
            }
            else
            {
                _scale = _size.Width / _unitWidth;
                _unitHeight = _size.Height / _scale;
                _distanceToView = (_unitWidth / 2d) / Math.Atan(_horizontalViewableAngle);
            }
        }
    }
}
